package com.ehotting.edsta.circuitDesign.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ehotting.edsta.circuitDesign.enums.DataTypeEnum;
import com.ehotting.edsta.circuitDesign.domain.EsElement;
import com.ehotting.edsta.circuitDesign.mapper.EsElementMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ehotting.edsta.circuitDesign.service.EsElementService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 元器件Service业务层处理
 * 
 * @author edsta
 * @date 2023-05-08
 */
@Service
public class EsElementServiceImpl implements EsElementService
{
    private static Logger logger = LoggerFactory.getLogger(EsElementServiceImpl.class);

    @Autowired
    private EsElementMapper esElementMapper;

    /**
     * 查询元器件
     * 
     * @param id 元器件主键
     * @return 元器件
     */
    @Override
    public EsElement selectEsElementById(Long id)
    {
        return esElementMapper.selectEsElementById(id);
    }

    /**
     * 查询元器件列表
     * 
     * @param esElement 元器件
     * @return 元器件
     */
    @Override
    public List<EsElement> selectEsElementList(EsElement esElement)
    {
        return esElementMapper.selectEsElementList(esElement);
    }

    /**
     * 新增元器件
     * 
     * @param esElement 元器件
     * @return 结果
     */
    @Override
    public int insertEsElement(EsElement esElement)
    {
        return esElementMapper.insertEsElement(esElement);
    }

    /**
     * 修改元器件
     * 
     * @param esElement 元器件
     * @return 结果
     */
    @Override
    public int updateEsElement(EsElement esElement)
    {
        return esElementMapper.updateEsElement(esElement);
    }

    /**
     * 批量删除元器件
     * 
     * @param ids 需要删除的元器件主键
     * @return 结果
     */
    @Override
    public int deleteEsElementByIds(Long[] ids)
    {
        return esElementMapper.deleteEsElementByIds(ids);
    }

    /**
     * 删除元器件信息
     * 
     * @param id 元器件主键
     * @return 结果
     */
    @Override
    public int deleteEsElementById(Long id)
    {
        return esElementMapper.deleteEsElementById(id);
    }


    @Override
    public List<EsElement> findByType(Integer type) {
        EsElement esElement = new EsElement();
        esElement.setType(type);
        return  selectEsElementList(esElement);
    }

    @Override
    public EsElement findOneByCode(String code) {
        EsElement esElement = new EsElement();
        esElement.setCode(code);
        List<EsElement> esElementList = selectEsElementList(esElement);
        if (esElementList.size() > 0){
            return esElementList.get(0);
        }

        return null;
    }

    @Override
    public boolean importExcel(MultipartFile file) {
        long startTime = System.currentTimeMillis();
        List<EsElement> esElementList = null;
        InputStream in = null;
        try {
            in = file.getInputStream();
            Workbook workbook = null;
            if (file.getOriginalFilename().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
            esElementList = analyzeExcel(workbook);

            logger.info("componentList.size():{}", esElementList.size());

            logger.info("Start save element");

            for (EsElement esElement : esElementList){
                insertEsElement(esElement);
            }

            logger.info("Finish import excel");

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }

    private List<EsElement> analyzeExcel(Workbook workbook){

        List<EsElement> list = new ArrayList<EsElement>();

        for (int numsheet = 0; numsheet < workbook.getNumberOfSheets(); numsheet++) {
            Sheet hssfSheet = workbook.getSheetAt(numsheet);
            if (hssfSheet == null) {
                logger.info("hssfSheet is null,continue.");
                continue;
            }
            bb:
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                Row xssfRow = hssfSheet.getRow(rowNum);
                if (xssfRow == null) {
                    logger.info("xssfRow is null,continue.");
                    continue bb;
                }
                EsElement esElement = handlerRow(xssfRow);
                if (esElement == null) {
                    continue bb;
                }

                list.add(esElement);
            }
        }
        return list;
    }

    private EsElement handlerRow(Row hssfRow) {
        EsElement esElement = new EsElement();
        boolean b = false;
        for (int i = 0; i < hssfRow.getLastCellNum(); i++) {
            Cell cell = hssfRow.getCell(i);
            if (cell == null) {
                logger.info("cell is null,return.");
                continue;
            }
            b = handlerCell(esElement, cell, i);

            if (!b){
                return null;
            }

        }
        return esElement;
    }

    private boolean handlerCell(EsElement esElement, Cell cell, int i) {
        cell.setCellType(CellType.STRING);

        try {
            if (i == 0) {
                esElement.setPriority(Long.valueOf(StringUtils.trim(cell.getStringCellValue())));
            } else if (i == 1) {
                esElement.setName(StringUtils.trim(cell.getStringCellValue()));
            } else if (i == 2) {
                esElement.setType(Integer.valueOf(StringUtils.trim(cell.getStringCellValue())));
            } else if (i == 3) {
                esElement.setDataType(DataTypeEnum.getObject(Integer.valueOf(StringUtils.trim(cell.getStringCellValue()))));
            } else if (i == 4) {
                esElement.setCode(StringUtils.trim(cell.getStringCellValue()));
            } else if (i == 5) {
                esElement.setValue(StringUtils.trim(cell.getStringCellValue()));
            } else if (i == 6) {
                esElement.setUnit(StringUtils.trim(cell.getStringCellValue()));
            } else if (i == 7) {
                esElement.setManufacturer(StringUtils.trim(cell.getStringCellValue()));
            } else if (i == 8) {
                esElement.setPrice(Double.valueOf(StringUtils.trim(cell.getStringCellValue())));
            } else if (i == 9) {
                esElement.setArea(Double.valueOf(StringUtils.trim(cell.getStringCellValue())));
            } else if (i == 10) {
                esElement.setPower(Double.valueOf(StringUtils.trim(cell.getStringCellValue())));
            } else if (i == 11) {
                if (!StringUtils.isBlank(StringUtils.trim(cell.getStringCellValue()))){
                    try {
                        Map<String, Object> map = JSONObject.parseObject(StringUtils.trim(cell.getStringCellValue()), Map.class);
                        esElement.setProps(map);
                    }catch (Exception e){

                    }
                }
            } else if (i == 12) {
                esElement.setRemarks(StringUtils.trim(cell.getStringCellValue()));
            }
        }catch (Exception e){
            return false;
        }

        return true;

    }


}
